Array: A special variable which can hold more than one value at a time, stored in an ordered list.
Method: A function that is a property of an object. Array methods are built-in functions we can call on any array.
Callback Function: A function passed into another function as an argument, which is then invoked inside the outer function. Many array methods use callbacks.
Mutability: The ability for an object's state to be modified after it's created. Mutating methods change the original array.
Immutability: The inability for an object's state to be modified. Non-mutating methods return a new array, leaving the original unchanged.
Higher-Order Function: A function that either takes one or more functions as arguments or returns a function as its result (e.g., map, filter).
๐งฎ Callback Function Syntax Pattern
Many modern array methods use a callback function that receives up to three arguments:
array.method((element, index, array) => {
// ... your logic here, operating on the element
});
element: The current element being processed in the array. (Required)
index: The index of the current element. (Optional)
array: The array the method was called upon. (Optional)
Example with Arrow Function:const doubled = [1, 2, 3].map(num => num * 2);
๐ ๏ธ Common Array Methods
Iteration Methods
Method
Description
Returns
forEach()
Executes a callback for each element in the array.
undefined
map()
Creates a new array by calling a function on every element.
New array
filter()
Creates a new array with all elements that pass a test (return true).
New array
Aggregation & Testing Methods
Method
Description
Returns
reduce()
Executes a reducer function to produce a single output value.
Single value
every()
Tests if all elements in the array pass a test.
Boolean
some()
Tests if at least one element in the array passes a test.
Boolean
Finding Methods
Method
Description
Returns
find()
Returns the first element that passes a test.
Element or undefined
findIndex()
Returns the index of the first element that passes a test.
Index or -1
includes()
Determines whether an array includes a certain value.
Boolean
Modification & Creation Methods
Method
Description
Type
push() / pop()
Adds/removes an element from the end of an array.
Mutating
unshift() / shift()
Adds/removes an element from the beginning of an array.
Mutating
splice()
Adds/removes elements from an array at a specified index.
Mutating
sort()
Sorts the elements of an array in place.
Mutating
slice()
Returns a shallow copy of a portion of an array into a new array.
Non-Mutating
concat()
Merges two or more arrays, returning a new array.
Non-Mutating
๐งญ Workflow: Choosing the Right Method
"I want to do something for each item." โ Use forEach().
"I want a new array with transformed items." โ Use map().
"I want a new array with a subset of items." โ Use filter().
"I want to check if any item meets a condition." โ Use some().
"I want to check if all items meet a condition." โ Use every().
"I want a single value calculated from the array." โ Use reduce().
"I want to find the first item that meets a condition." โ Use find().
"I want to change the original array." โ Use push(), pop(), splice(), etc.
โจ๏ธ Productivity Tips
Method Chaining: Since many methods return a new array, you can chain them together for powerful, concise operations.
const result = users.filter(u => u.isActive).map(u => u.name);
Arrow Functions: Use arrow functions for callbacks to make your code much cleaner and more readable.
Spread Syntax (`...`): Use the spread syntax for an immutable way to add items to an array.
const newArr = [...oldArr, newItem]; // Like push, but immutable
๐ Mutating vs. Non-Mutating
Understanding this distinction is crucial for avoiding bugs.
Given an array of order objects, find the total revenue from all completed orders placed by customers in the USA.
const orders = [
{ id: 1, country: 'USA', status: 'completed', revenue: 100 },
{ id: 2, country: 'CAN', status: 'completed', revenue: 150 },
{ id: 3, country: 'USA', status: 'pending', revenue: 80 },
{ id: 4, country: 'USA', status: 'completed', revenue: 200 },
];
const totalUSARevenue = orders
.filter(order => order.country === 'USA' && order.status === 'completed') // 1. Get only completed US orders
.map(order => order.revenue) // 2. Get an array of just their revenue values
.reduce((sum, currentRevenue) => sum + currentRevenue, 0); // 3. Sum up the values
console.log(totalUSARevenue); // Output: 300
๐งน Troubleshooting Common Errors
Error: .sort() doesn't work for numbers.
Fix: By default, sort() sorts elements as strings. You must provide a compare function: arr.sort((a, b) => a - b) for ascending order.
Error: Modifying an array while iterating with forEach.
Fix: This can lead to unpredictable behavior. If you need to modify an array based on its elements, it's often safer to create a new array using map or filter, or iterate backwards with a standard `for` loop.
Error: reduce on an empty array with no initial value.
Fix: This throws a TypeError. Always provide an initial value to reduce to handle empty arrays gracefully: arr.reduce(callback, initialValue).
Confusion: slice() vs. splice().
Fix: Remember "Splice changes, Slice serves." splice() modifies the original array, while slice() returns a new, shallow copy of a portion of it.